'''
Created on Jun 29, 2011

@author: peterd
'''

from django.core.exceptions import ObjectDoesNotExist

from infra.util.geoutil import getBoundingBox, LatLng
from geo.Radius import Radius
from web.service.DirectionBroker import DirectionBroker

from mhd.models import MHD_Stop, MHD_Stop_Transfer, MHD_Stop_Navigation
from mhd.conf import num_direction_retries

def main():
    for stop in MHD_Stop.objects.all():
        from_stop = stop
        #from_stop = MHD_Stop.objects.get(id = 6)
        if from_stop.lat == 0.0 or from_stop.lng == 0.0:
            continue
        
        print "looking for stops near by %s" % from_stop

        boundingBox = getBoundingBox(from_stop.lat, from_stop.lng, Radius(500, 'm'))
        directionBroker = DirectionBroker(use_proxy = True)
        
        nearby_stops = MHD_Stop.objects.filter(lat__gte = boundingBox.north()).filter(lat__lte = boundingBox.south()).filter(lng__gte = boundingBox.west()).filter(lng__lte = boundingBox.east())
        for nearby_stop in nearby_stops:
            if nearby_stop.id == from_stop.id:  # or nearby_stop.lat == 0.0: 
                continue
            
            print "nearby stop.id: %d" % nearby_stop.id
            
            distance = None
            duration = None
            retry = num_direction_retries
            steps = []                
                
            mhd_stop_transfer = None
            try:
                mhd_stop_transfer = MHD_Stop_Transfer.objects.get(from_stop = from_stop, to_stop = nearby_stop)
                print "already calculated"                    
            except ObjectDoesNotExist:
                while not distance and retry != 0:
                    (distance, duration) = directionBroker.getWalkingDistance(LatLng(from_stop.lat, from_stop.lng), nearby_stop)
                    steps = directionBroker.getSteps()
                    retry = retry - 1
			
                if not distance:
                    distance = -1
                    duration = 'unknown'
            	
                mhd_stop_transfer = MHD_Stop_Transfer(from_stop = from_stop, to_stop = nearby_stop, distance = distance, duration = duration[0:9]) 
                print "distance: %d, duration: %s" % (distance, duration)               
                mhd_stop_transfer.save()
            
                MHD_Stop_Navigation.objects.filter(stop_transfer = mhd_stop_transfer).delete()
                for step in steps:
                    mhd_stop_navigation = MHD_Stop_Navigation(stop_transfer = mhd_stop_transfer, distance = step['distance']['value'], duration = step['duration']['text'], instructions = step['html_instructions'])
                    mhd_stop_navigation.save()

            

if __name__ == '__main__':
    main()